import '../models/directory_model.dart';
import '../models/file_model.dart';
import '../services/api_service.dart';
import '../models/api_response.dart';
import 'package:flutter/foundation.dart';

class DirectoryService {
  // 获取目录列表
  Future<List<DirectoryModel>> getDirectories({int? parentId}) async {
    final response = await ApiService.get<List<dynamic>>(
      '/directories',
      queryParams: parentId != null ? {'parent_id': parentId.toString()} : null,
      fromJson: (json) => (json['items'] as List).cast<dynamic>(),
    );

    return response.data!
        .map((item) => DirectoryModel.fromJson(item as Map<String, dynamic>))
        .toList();
  }

  // 获取目录树
  Future<List<DirectoryModel>> getDirectoryTree() async {
    final response = await ApiService.get<List<dynamic>>(
      '/directories/tree',
      fromJson: (json) => (json['tree'] as List).cast<dynamic>(),
    );

    return response.data!
        .map((item) => DirectoryModel.fromJson(item as Map<String, dynamic>))
        .toList();
  }

  // 获取目录详情
  Future<DirectoryModel> getDirectoryDetail(int directoryId) async {
    final response = await ApiService.get<Map<String, dynamic>>(
      '/directories/$directoryId',
      fromJson: (json) => json as Map<String, dynamic>,
    );

    return DirectoryModel.fromJson(response.data!);
  }

  // 在指定目录下查找同名目录
  Future<DirectoryModel?> findDirectory(String name, {int parentId = 0}) async {
    debugPrint('尝试查找目录: 名称[$name], 父目录ID[$parentId]');

    try {
      final directories = await getDirectories(parentId: parentId);

      for (var dir in directories) {
        if (dir.name == name) {
          debugPrint('找到已存在的目录: ${dir.id}, 名称[$name]');
          return dir;
        }
      }

      debugPrint('未找到同名目录: 名称[$name], 父目录ID[$parentId]');
      return null;
    } catch (e) {
      debugPrint('查找目录时出错: $e');
      return null;
    }
  }

  // 创建目录
  Future<DirectoryModel> createDirectory(
    String name, {
    int parentId = 0,
  }) async {
    // 验证目录名不为空
    if (name.trim().isEmpty) {
      debugPrint('错误: 尝试创建目录时名称为空');
      throw Exception('目录名不能为空');
    }

    debugPrint('发起创建目录请求: 名称[$name], 父目录ID[$parentId]');

    try {
      final response = await ApiService.post<Map<String, dynamic>>(
        '/directories',
        body: {'name': name, 'parent_id': parentId},
        fromJson: (json) => json as Map<String, dynamic>,
      );

      debugPrint('创建目录成功: ${response.data?['id']}');
      return DirectoryModel.fromJson(response.data!);
    } catch (e) {
      debugPrint('创建目录失败: $e');

      // 检查错误信息是否包含"目录已存在"
      if (e.toString().contains('同级目录下已存在')) {
        debugPrint('目录已存在，尝试查找现有目录');
        final existingDir = await findDirectory(name, parentId: parentId);
        if (existingDir != null) {
          debugPrint('找到现有目录: ${existingDir.id}');
          return existingDir;
        }
      }

      // 如果不是目录已存在错误，或者找不到现有目录，则重新抛出异常
      rethrow;
    }
  }

  // 更新目录
  Future<DirectoryModel> updateDirectory(
    int directoryId, {
    String? name,
    int? parentId,
  }) async {
    final Map<String, dynamic> body = {};
    if (name != null) body['name'] = name;
    if (parentId != null) body['parent_id'] = parentId;

    final response = await ApiService.put<Map<String, dynamic>>(
      '/directories/$directoryId',
      body: body,
      fromJson: (json) => json as Map<String, dynamic>,
    );

    return DirectoryModel.fromJson(response.data!);
  }

  // 删除目录
  Future<bool> deleteDirectory(
    int directoryId, {
    bool permanent = false,
  }) async {
    final response = await ApiService.delete<Map<String, dynamic>>(
      '/directories/$directoryId',
      queryParams: {'permanent': permanent.toString()},
    );

    return response.code == 200;
  }

  // 移动文件或目录
  Future<Map<String, dynamic>> moveItems({
    List<int>? fileIds,
    List<int>? directoryIds,
    required int targetDirectoryId,
  }) async {
    final Map<String, dynamic> body = {
      'target_directory_id': targetDirectoryId,
    };

    if (fileIds != null && fileIds.isNotEmpty) {
      body['file_ids'] = fileIds;
    }

    if (directoryIds != null && directoryIds.isNotEmpty) {
      body['directory_ids'] = directoryIds;
    }

    final response = await ApiService.post<Map<String, dynamic>>(
      '/directories/move-items',
      body: body,
      fromJson: (json) => json as Map<String, dynamic>,
    );

    return response.data!;
  }

  // 获取目录下的文件
  Future<List<FileModel>> getDirectoryFiles(int directoryId) async {
    final response = await ApiService.get<List<dynamic>>(
      '/directories/$directoryId/files',
      fromJson: (json) => (json['items'] as List).cast<dynamic>(),
    );

    return response.data!
        .map((item) => FileModel.fromJson(item as Map<String, dynamic>))
        .toList();
  }
}
